package ru.tairov.rtsedd.mongodb;

import java.net.UnknownHostException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

@Configuration
public class ApplicationConfiguration {

    @Value("${db.app.name}")
    private String appDbName;

    @Value("${db.host}")
    private String dbHost;

   @Value("${db.port}")
   private String dbPort;
   
   @Value("${db.user}")
   private String dbUser;
   
   @Value("${db.password}")
   private String dbPassword;


   @Bean
   public DB db() throws UnknownHostException {
       DB db = mongo().getDB(appDbName);
       
       /*DBCollection coll = db.getCollection("test");
       
       if (coll == null) {
    	   db.createCollection("test", null);
       }*/
       
       if (dbUser != null && !dbUser.equals("${db.user}")) {
    	   db.authenticate(dbUser, dbPassword.toCharArray());
       }
       
       return db;
   }

   @Bean
   public Mongo mongo() throws UnknownHostException {
       return new Mongo(dbHost, Integer.parseInt(dbPort));
       
       
   }
}
